package chat.server;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

import javax.xml.ws.handler.MessageContext.Scope;

import chat.user.*;

public class ServerThread extends Thread {

	private Socket socket;
	private ObjectInputStream ois;
	private Object input;
	// private GroupProcessor group_processor;

	// private SocketProcessor socket_processor;
	private Message n;

	public ServerThread(Socket s) throws IOException {

		socket = s;
		// group_processor = groups;
		// socket_processor = proc;

		start();
	}

	@Override
	public void run() {

		try {

			while (true) {

				ois = new ObjectInputStream(new BufferedInputStream(
						socket.getInputStream()));

				Request r = (Request) ois.readObject();

				if (r instanceof RequestDisconnect) {

					/*RequestDisconnect request = (RequestDisconnect) r;

					User user = GroupProcessor.getGroup(
							request.getUser().getRelatedGroup()).getUser(
							request.getUser().getUserName());

					//MultiThread.disconnectThread(this, socket, ois);
					SocketProcessor.addMessageOutQueue(MessageCreator
							.requestDisconnectResponse(user));*/
				} else if (r instanceof RequestAuth) {
					RequestAuth request = (RequestAuth) r;
					GroupProcessor.registerNewUser(socket, request.getUser());
					MessageCreator.AuthRequestResponse(request.getUser());
					SocketProcessor.addMessageOutQueue(MessageCreator
							.AuthRequestResponse(request.getUser()));
					MultiThread
							.addClient(request.getUser().getUserName(), this);

				}

				MultiThread.addInMessage(r);
				sleep(10);
			}
			
		}

		catch (Exception e) {

			e.printStackTrace();
		}
	}

	public Socket getSocket() {
		return socket;
	}

	public boolean disconect() {

		{
			try {
				ois.close();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				this.interrupt();
			}

			return true;

		}
	}
}
